package com.warren.system.controller;

import com.warren.response.Result;
import com.warren.system.entity.File;
import com.warren.system.service.AliOssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author warren
 * @date 2021/3/24 0024 11:50
 * @Description
 **/
@Slf4j
@Api(value = "oss",tags = "oss操作接口")
@RestController
public class AliOssController {

    @Autowired
    private AliOssService aliOssService;

    @ApiOperation(value = "图片上传", notes = "根据文件名上传")
    @PostMapping("/uploadImgFile")
    public Result upload( MultipartFile file){
        System.out.println(file);
        File upload = aliOssService.upload(file);
        String url = upload.getUrl();

        return Result.ok().data("url",url).data("file",upload);
    }

    @ApiOperation(value = "图片删除",notes = "删除替换之后的头像")
    @PostMapping("/deleteImgFile")
    public Result deleteImgFile(String file){
        try {
            String[] split = file.split(".com/");
            aliOssService.deleteFile(split[1]);
            return Result.ok().message("删除ailOss成功");
        } catch (Exception exception) {
            log.info("删除失败信息"+exception);
            return Result.error().message("删除aliOss文件失败");
        }
    }

    @ApiOperation("oss批量删除文件")
    @PostMapping("/deleteFiles")
    public Result deleteFiles(String files){
        String[] urlList = files.split(",");
        if (urlList.length > 0){
            for (String s : urlList){
                String[] split = s.split("com/");
                aliOssService.deleteFile(split[1]);
            }
        }
        return Result.ok().message("删除aliOss文件成功");
    }

    @ApiOperation(value = "文件下载",notes = "附件文件下载")
    @PostMapping("/fileDownload")
    public void fileDownload(String file, HttpServletResponse response) throws InterruptedException , IOException{
        response.setHeader("content-type","application/octet-stream");
        response.setHeader("content-disposition","attachment:filename="+ URLEncoder.encode(file,"UTF-8"));
        aliOssService.downLoadFile(response,file);
    }
}
